package pl.edu.agh.jemo.evolution.metrics;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

import pl.edu.agh.jemo.evolution.population.Population;

public final class MetricEvaluator {

	private Logger logger = Logger.getLogger(MetricEvaluator.class);
	
	private final Set<Metric> metrics = new HashSet<Metric>();
	
	private final String dirname;
	
	int counter = 0;
	
	public void addMetric(final Metric metric) throws IOException {
		metrics.add(metric);
	}

	public void evaluate(final Population population) {
		for (final Metric metric : metrics) {
			final BigDecimal value = metric.getValue(population);
			//results.get(metric.getName()).add(value);
			logger.debug(metric.getName() + " value: " + value);
			File dir = new File(".\\metryki\\" + dirname);
			BufferedWriter out;
			try {
				out = new BufferedWriter(new FileWriter(dir
						.getCanonicalPath()
						+ "\\" + metric.getName() + ".txt", true));
				out.append(counter + " " + value.doubleValue() + "\r\n");
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		counter++;
	}
	
	
	public MetricEvaluator() {
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
		Calendar cal = Calendar.getInstance();
		dirname = dateFormat.format(cal.getTime());
		(new File(".\\metryki\\" + dirname)).mkdir();
	}
}
